Imports MIMS.WRS.Entities
Imports MIMS.WRS.Business
Imports MyFramework

Public Class ConPointDetail1
    Inherits System.Web.UI.UserControl

#Region " Web Form Designer Generated Code "

    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

    End Sub
    Protected WithEvents ltrMessage As System.Web.UI.WebControls.Literal
    Protected WithEvents txtDescription As System.Web.UI.WebControls.TextBox
    Protected WithEvents Requiredfieldvalidator2 As System.Web.UI.WebControls.RequiredFieldValidator
    Protected WithEvents btnOK As System.Web.UI.WebControls.Button
    Protected WithEvents btnCancel As System.Web.UI.WebControls.Button
    Protected WithEvents txtGoods As System.Web.UI.WebControls.TextBox
    Protected WithEvents chkDisplay As System.Web.UI.WebControls.CheckBox
    Protected WithEvents txtContainerLoading As System.Web.UI.WebControls.TextBox
    Protected WithEvents txtLoadingPort As System.Web.UI.WebControls.TextBox
    Protected WithEvents rptResponsibles As System.Web.UI.WebControls.Repeater
    Protected WithEvents txtNewName As System.Web.UI.WebControls.TextBox
    Protected WithEvents ddlNewOffice As System.Web.UI.WebControls.DropDownList
    Protected WithEvents btnAddResp As System.Web.UI.WebControls.Button
    Protected WithEvents pnlResp As System.Web.UI.WebControls.Panel
    Protected WithEvents ValidationSummary1 As System.Web.UI.WebControls.ValidationSummary
    Protected WithEvents ddlNewResponsible As System.Web.UI.WebControls.DropDownList
    Protected WithEvents txtTallPalletVol As System.Web.UI.WebControls.TextBox
    Protected WithEvents txtHalfPalletVol As System.Web.UI.WebControls.TextBox
    Protected WithEvents btnDeleteUnit As System.Web.UI.WebControls.Button
    Protected WithEvents rptUnitSettings As System.Web.UI.WebControls.Repeater
    Protected WithEvents cboUnitsNew As System.Web.UI.WebControls.DropDownList
    Protected WithEvents txtCbmValueNew As System.Web.UI.WebControls.TextBox
    Protected WithEvents btnAddUnitSetting As System.Web.UI.WebControls.Button
    Protected WithEvents btnDelete As System.Web.UI.WebControls.Button
    Protected WithEvents pnlUnitSetting As System.Web.UI.WebControls.Panel

    'NOTE: The following placeholder declaration is required by the Web Form Designer.
    'Do not delete or move it.
    Private designerPlaceholderDeclaration As System.Object

    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent()
    End Sub

#End Region
    Protected mainObj As ConPoint = Nothing

    Private isInUse As Boolean = False

    Protected Property ReferrerUrl() As String
        Get
            Return Convert.ToString(ViewState("ReferrerUrl"))
        End Get
        Set(ByVal Value As String)
            ViewState("ReferrerUrl") = Value
        End Set
    End Property

    Protected ReadOnly Property IsAddNew() As Boolean
        Get
            Return RequestContext.ConPointID = 0
        End Get
    End Property

    Private Function BuildObject() As Boolean
        If IsAddNew Then
            mainObj = New ConPoint
        Else
            mainObj = ConPointService.GetConPoint(RequestContext.ConPointID)
            If mainObj Is Nothing Then
                Utilities.ShowMessagePage("Failed to load requested! Consolidation Point may be deleted or not found")
                Return False
            End If
        End If

        Return True
    End Function

    Private Sub UpdateData(ByVal bSave As Boolean)
        If (bSave) Then
            mainObj.Description = txtDescription.Text
            mainObj.Goods = txtGoods.Text
            mainObj.IsDisplayed = chkDisplay.Checked
            mainObj.ContainerLoading = txtContainerLoading.Text
            mainObj.LoadingPort = txtLoadingPort.Text
            Try
                mainObj.TallPalletVol = Convert.ToDecimal(txtTallPalletVol.Text)
            Catch ex As Exception
            End Try
            Try
                mainObj.HalfPalletVol = Convert.ToDecimal(txtHalfPalletVol.Text)
            Catch ex As Exception
            End Try
        Else
            txtDescription.Text = mainObj.Description
            txtGoods.Text = mainObj.Goods
            chkDisplay.Checked = mainObj.IsDisplayed
            txtContainerLoading.Text = mainObj.ContainerLoading
            txtLoadingPort.Text = mainObj.LoadingPort
            'new 2 volums
            txtTallPalletVol.Text = mainObj.TallPalletVol.ToString()
            txtHalfPalletVol.Text = mainObj.HalfPalletVol.ToString()

            LoadResponsibles()
            LoadUnitSettings()
        End If
    End Sub

    Private Sub LoadResponsibles()
        ReBuildObject()

        ddlNewOffice.DataSource = OfficeService.GetOffices(RequestContext.CurrentUser.US_ID_PK)
        ddlNewOffice.DataTextField = OfficeColumns.OfficeName.ToString()
        ddlNewOffice.DataValueField = OfficeColumns.OfficeID.ToString()
        ddlNewOffice.DataBind()
        ddlNewOffice.Items.Insert(0, New ListItem("", Nulls.NullInteger.ToString()))

        ddlNewResponsible.DataSource = ResponsibleService.GetResponsiblesByConPoint(mainObj.ConPointID)
        ddlNewResponsible.DataTextField = ResponsibleColumns.Name.ToString()
        ddlNewResponsible.DataValueField = ResponsibleColumns.ResponsibleID.ToString()
        ddlNewResponsible.DataBind()
        ddlNewResponsible.Items.Insert(0, New ListItem("[new responsible -->]", Nulls.NullInteger.ToString()))

        rptResponsibles.DataSource = ResponsibleOfficeService.GetResponsibleOfficesByConPoint(mainObj.ConPointID)
        rptResponsibles.DataBind()
    End Sub

    Private Sub ReBuildObject()
        If (mainObj Is Nothing) Then
            mainObj = ConPointService.GetConPoint(RequestContext.ConPointID)
        End If
    End Sub

    Private Sub LoadUnitSettings()
        'new unit setting
        cboUnitsNew.DataSource = UnitSettingService.GetUnitSettingsOnly()
        cboUnitsNew.DataTextField = UnitSettingColumns.Description.ToString()
        cboUnitsNew.DataValueField = UnitSettingColumns.UnitSettingID.ToString()
        cboUnitsNew.DataBind()
        cboUnitsNew.Items.Insert(0, New ListItem("", ""))

        txtCbmValueNew.Text = ""

        ReBuildObject()
        rptUnitSettings.DataSource = UnitSettingService.GetUnitSettingsOnlyByConPoint(mainObj.ConPointID)
        rptUnitSettings.DataBind()
    End Sub

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        If RequestContext.CurrentUser.IS_ADMIN = False Then
            btnDelete.Visible = False

        End If

        btnAddResp.Attributes("onclick") = "if (!validateAdd()) return false;"

        If Not IsPostBack Then
            ReferrerUrl = Utilities.GetReferrerUrl("ConPointList.aspx")


            If IsAddNew Then
                btnDelete.Visible = False
                chkDisplay.Checked = True
                pnlResp.Visible = False
                pnlUnitSetting.Visible = False
            Else
                pnlResp.Visible = True
                pnlUnitSetting.Visible = True
                If (BuildObject()) Then
                    UpdateData(False)
                End If
                btnDelete.Attributes("onclick") = "return confirm('Are you sure you want to delete?');"
                btnDelete.Visible = True
            End If
        End If
    End Sub

    Private Function IsConPointExisted() As Boolean
        Dim dummy As ConPoint = ConPointService.GetConPoint(mainObj.Description)
        If Not (dummy Is Nothing) Then
            ltrMessage.Text = "Consolidation Point has already existed. Please enter another."
            Return True
        Else
            Return False
        End If
    End Function

    Private Sub btnOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOK.Click
        If (Page.IsValid) Then
            'check for duplicate responsibles
            Dim isDuplicate As Boolean = False
            Dim respOffices As New ResponsibleOfficeCollection

            For Each ri As RepeaterItem In rptResponsibles.Items
                Dim ddlResponsible As DropDownList = CType(ri.FindControl("ddlResponsible"), DropDownList)
                Dim txtName As TextBox = CType(ri.FindControl("txtName"), TextBox)
                Dim ddlOffice As DropDownList = CType(ri.FindControl("ddlOffice"), DropDownList)

                For Each respOffice As ResponsibleOffice In respOffices
                    If respOffice.ResponsibleID = Convert.ToInt32(ddlResponsible.SelectedItem.Value) _
                        AndAlso respOffice.DefaultToOfficeID = Convert.ToInt32(ddlOffice.SelectedItem.Value) Then
                        isDuplicate = True
                        Exit For
                    End If
                Next

                If isDuplicate Then
                    Exit For
                Else
                    Dim respOffice As New ResponsibleOffice
                    respOffice.DefaultToOfficeID = Convert.ToInt32(ddlOffice.SelectedItem.Value)
                    respOffice.ResponsibleID = Convert.ToInt32(ddlResponsible.SelectedItem.Value)
                    respOffices.Add(respOffice)
                End If
            Next

            If isDuplicate Then
                ltrMessage.Text = "There is duplicate responsible. Please check again!"
                Return
            End If

            If (isDuplicate = False AndAlso BuildObject()) Then
                Dim oldDescription As String = mainObj.Description
                UpdateData(True)
                If IsAddNew Then
                    If IsConPointExisted() = True Then Return
                    ConPointService.CreateConPoint(mainObj)
                Else
                    If Not oldDescription.ToLower().Trim().Equals(mainObj.Description.ToLower().Trim()) Then
                        If IsConPointExisted() = True Then Return
                    End If
                    ConPointService.UpdateConPoint(mainObj)

                    ' update responsible                  
                    ResponsibleOfficeService.UpdateResponsibleOfficeBatch(respOffices, mainObj.ConPointID)

                End If

                'Update Unit settings
                MassUpdateForUnitSettings(mainObj.ConPointID)
                Response.Redirect(ReferrerUrl)
            End If
       
        End If
    End Sub

    Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click
        ConPointService.DeleteConPoint(RequestContext.ConPointID)
        Response.Redirect(ReferrerUrl)
    End Sub

    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        Response.Redirect(ReferrerUrl)
    End Sub

    Private Sub rptResponsibles_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles rptResponsibles.ItemDataBound
        If (e.Item.ItemType = ListItemType.Item OrElse e.Item.ItemType = ListItemType.AlternatingItem) Then
            Dim ddlOffice As DropDownList = CType(e.Item.FindControl("ddlOffice"), DropDownList)
            Dim ddlResponsible As DropDownList = CType(e.Item.FindControl("ddlResponsible"), DropDownList)
            Dim respOffice As ResponsibleOffice = CType(e.Item.DataItem, ResponsibleOffice)

            ddlResponsible.DataSource = ResponsibleService.GetResponsiblesByConPoint(mainObj.ConPointID)
            ddlResponsible.DataTextField = ResponsibleColumns.Name.ToString()
            ddlResponsible.DataValueField = ResponsibleColumns.ResponsibleID.ToString()
            ddlResponsible.DataBind()
            Try
                ddlResponsible.SelectedIndex = ddlResponsible.Items.IndexOf(ddlResponsible.Items.FindByValue(respOffice.ResponsibleID.ToString()))
            Catch ex As Exception

            End Try

            ddlOffice.DataSource = OfficeService.GetOffices(RequestContext.CurrentUser.US_ID_PK)
            ddlOffice.DataTextField = OfficeColumns.OfficeName.ToString()
            ddlOffice.DataValueField = OfficeColumns.OfficeID.ToString()
            ddlOffice.DataBind()
            ddlOffice.Items.Insert(0, New ListItem("", Nulls.NullInteger.ToString()))
            Try
                ddlOffice.SelectedIndex = ddlOffice.Items.IndexOf(ddlOffice.Items.FindByValue(respOffice.DefaultToOfficeID.ToString()))
            Catch ex As Exception

            End Try

            Dim btnDeleteResp As Button = CType(e.Item.FindControl("btnDeleteResp"), Button)
            If (respOffice.IsInUse) Then
                btnDeleteResp.Enabled = False
                btnDelete.Enabled = False
            Else
                btnDeleteResp.Attributes("onclick") = "if (!confirm('Are you sure you want to remove this Responsible?')) return false;"
            End If

        End If
    End Sub

    Private Sub btnAddResp_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddResp.Click
        Try
            Dim respOffice As New ResponsibleOffice

            respOffice.ResponsibleName = txtNewName.Text.Trim()
            respOffice.ResponsibleID = Convert.ToInt32(ddlNewResponsible.SelectedItem.Value)
            respOffice.DefaultToOfficeID = Convert.ToInt32(ddlNewOffice.SelectedItem.Value)
            ResponsibleOfficeService.CreateResponsibleOfficeBatch(respOffice, RequestContext.ConPointID)

            LoadResponsibles()
            'Response.Redirect(Request.RawUrl)
        Catch ex As Exception
            ltrMessage.Text = "Can not add responsible! Please try again or contact administrator!"
        End Try
    End Sub

    Private Sub rptResponsibles_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.RepeaterCommandEventArgs) Handles rptResponsibles.ItemCommand
        If (e.Item.ItemType = ListItemType.Item OrElse e.Item.ItemType = ListItemType.AlternatingItem) Then
            Select Case e.CommandName.ToLower()
                Case "delete"
                    Dim respID As Integer = Convert.ToInt32(e.CommandArgument)
                    ResponsibleService.DeleteResponsible(respID)
                    'Response.Redirect(Request.RawUrl)
                    LoadResponsibles()
            End Select
        End If
    End Sub

#Region "Unit settings"

    Private Sub MassUpdateForUnitSettings(ByVal conPointID As Integer)
        Dim unitSettings As New UnitSettingCollection

        For Each ri As RepeaterItem In rptUnitSettings.Items
            Dim ddlResponsible As DropDownList = CType(ri.FindControl("ddlResponsible"), DropDownList)
            Dim txtName As TextBox = CType(ri.FindControl("txtName"), TextBox)
            Dim ddlOffice As DropDownList = CType(ri.FindControl("ddlOffice"), DropDownList)

            Dim cboUnits As DropDownList = CType(ri.FindControl("cboUnits"), DropDownList)
            Dim txtCbmValue As TextBox = CType(ri.FindControl("txtCbmValue"), TextBox)
            Dim unitSettingObj As New UnitSetting

            unitSettingObj.ConPointID = conPointID
            Try
                unitSettingObj.UnitSettingID = Convert.ToInt32(cboUnits.SelectedItem.Value)
            Catch ex As Exception
            End Try
            Try
                unitSettingObj.CbmValue = Convert.ToDecimal(txtCbmValue.Text)
            Catch ex As Exception
            End Try
            unitSettings.Add(unitSettingObj)
        Next
        Try
            UnitSettingService.UpdateUnitSettingForConPointBatch(unitSettings, RequestContext.ConPointID)
        Catch ex As Exception
            ltrMessage.Text = "Can not update unit settings! Please try again or contact administrator!"
        End Try
    End Sub
    Private Sub rptUnitSettings_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles rptUnitSettings.ItemDataBound
        If (e.Item.ItemType = ListItemType.Item OrElse e.Item.ItemType = ListItemType.AlternatingItem) Then
            Dim cboUnits As DropDownList = CType(e.Item.FindControl("cboUnits"), DropDownList)
            Dim txtCbmValue As TextBox = CType(e.Item.FindControl("txtCbmValue"), TextBox)
            Dim unitSettingObj As UnitSetting = CType(e.Item.DataItem, UnitSetting)

            cboUnits.DataSource = UnitSettingService.GetUnitSettingsOnly()
            cboUnits.DataTextField = UnitSettingColumns.Description.ToString()
            cboUnits.DataValueField = UnitSettingColumns.UnitSettingID.ToString()
            cboUnits.DataBind()
            Try
                cboUnits.SelectedIndex = cboUnits.Items.IndexOf(cboUnits.Items.FindByValue(unitSettingObj.UnitSettingID.ToString()))
            Catch ex As Exception

            End Try

            Try
                txtCbmValue.Text = unitSettingObj.CbmValue.ToString()
            Catch ex As Exception

            End Try

            Dim btnDeleteUnit As Button = CType(e.Item.FindControl("btnDeleteUnit"), Button)
            If (unitSettingObj.IsInUse) Then
                btnDeleteUnit.Enabled = False
                btnDeleteUnit.Enabled = False
            Else
                btnDeleteUnit.Attributes("onclick") = "if (!confirm('Are you sure you want to remove this item?')) return false;"
            End If

        End If
    End Sub

    Private Sub rptUnitSettings_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.RepeaterCommandEventArgs) Handles rptUnitSettings.ItemCommand
        If (e.Item.ItemType = ListItemType.Item OrElse e.Item.ItemType = ListItemType.AlternatingItem) Then
            Select Case e.CommandName.ToLower()
                Case "deleteunit"
                    Dim unitSettingID As Integer = Convert.ToInt32(e.CommandArgument)
                    UnitSettingService.DeleteUnitSettingByConPoint(RequestContext.ConPointID, unitSettingID)
                    LoadUnitSettings()
                    'Response.Redirect(Request.RawUrl)
            End Select
        End If
    End Sub

    Private Sub btnAddUnitSetting_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddUnitSetting.Click
        If (cboUnitsNew.SelectedItem.Value = "") Then
            Return
        End If
        Try
            Dim unitSettingObj As New UnitSetting

            unitSettingObj.UnitSettingID = Convert.ToInt32(cboUnitsNew.SelectedItem.Value)
            unitSettingObj.ConPointID = RequestContext.ConPointID
            Try
                unitSettingObj.CbmValue = Convert.ToDecimal(txtCbmValueNew.Text)
            Catch ex As Exception
            End Try

            UnitSettingService.CreateUnitSettingForConPoint(unitSettingObj)

            LoadUnitSettings()
            'Response.Redirect(Request.RawUrl)
        Catch ex As Exception
            ltrMessage.Text = "Can not add unit setting! Please try again or contact administrator!"
        End Try
    End Sub

#End Region



End Class
